package BinarySearch;

import java.util.Arrays;

/**
 * Copyright (C), 2020-2020, XXX有限公司
 * FileName: BinarySearchrecursion
 * Author:   cakin
 * Date:     2020/1/6
 * Description: 用递归方法实现二分法查找
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
public class BinarySearchrecursion {
    public static int rank(int key,int[]a){
        return rank(key,a,0,a.length-1);
    }

    public static int rank(int key,int[] a,int lo,int hi){
        if(lo>hi){
            return -1;      // 找不到就返回-1
        }
        int mid = lo + (hi - lo) / 2;
        if (key < a[mid]){
            return rank(key,a,lo,mid-1);        // 左半边找
        }
        else if (key > a[mid]){
            return rank(key,a,mid+1,hi);        // 右半边找
        }
        else{
            return mid;     // 找到了就返回下标
        }
    }

    public static void main( String[] args ) {
        int[] whitelist = {1,56,43,87,34,98,23,76};

        // 排序
        Arrays.sort(whitelist);
        System.out.println(rank(10,whitelist));     // 找不到
        System.out.println(rank(34,whitelist));     // 找到了
    }
}
